package com.yang.xiao.hui.servlet;

import com.yang.xiao.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class DispatcherServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = req.getServletContext();
        String controller = (String)servletContext.getAttribute("controller");
        try {
            Class<?> aClass = Class.forName(controller);
            Method[] declaredMethods = aClass.getDeclaredMethods();

            String requestURI = req.getRequestURI();
            Object o = aClass.newInstance();
            Method  finalMethod=null;
            for (Method method : declaredMethods) {
               if(!method.isAnnotationPresent(RequestMapping.class)){
                   continue;
               }
                RequestMapping reqMapping = method.getAnnotation(RequestMapping.class);
                String url = reqMapping.url();
                if(requestURI.equals(url)){
                    finalMethod=method;
                    break;
                }

            }
            if(finalMethod!=null){
                Object invoke = finalMethod.invoke(o);
                resp.getWriter().print(invoke);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
